from expression import expression
from customExceptions import ReturnExcpt
import sys
sys.path.append(sys.path[0] + "/../LLVM")
from llvmhelper import llvmHelper
from llvm import *
from commonRoutines import commonRoutines

class Return(expression):
	def __init__(self, expr):
		self.expr = expr
	def evaluate(self, env):
		#print "Returning: ", self.expr
		try:
			#print "Ret Env: \n", str(env)
			value = self.expr.evaluate(env)
			#print "Evaluated value: ", value
		except ReturnExcpt:
			print "ERROR: What the heck, a return in a return?"
		else:
			raise ReturnExcpt(value)
			
	def toLLVM(self, helper):
		helper.descend("Return")
		self.expr.toLLVM(helper)
		
		endReg = helper.getReturns()
		
		helper.addLLVMInst(llvm_ret(endReg[0]))
		
		helper.setLabel(helper.getLastLabel())
		helper.ascend(endReg[0])

	def __str__(self):
		return "return(" + str(self.expr) + ")"
	
	def traverse(self, helper):
		self.expr.traverse(helper)
